<?php

namespace app\api\controller;

use addons\shopro\model\UserWalletLog;
use app\common\controller\Api;
use app\common\model\RetailUser;
use think\Db;
use think\Exception;
use addons\shopro\model\Order;
use addons\shopro\model\OrderItem;
use addons\shopro\model\User;
use addons\shopro\model\Giftlog;
use app\common\model\RetailConfig;


/**
 * 分销相关接口
 */
class Bargain extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    //线上砍价活动列表
    public function bargainirgAction()
    {
        $type = 0;
        $way = input('param.way', '','string');
        if (!empty($way) && $way == 'live') {
            $type = 1;
        }
        $pageSize = 10;
        if (Request::isAjax()) {
            $page = input('post.page', 0, 'intval');
            $product_list = Hmodel\Activity::getActivityBargainProducts($type, $pageSize,  $page * $pageSize);
            if (!empty($product_list)) {
                return json_encode(['status' => 1, 'info' => $product_list]);
            } else {
                return json_encode(['status' => 0]);
            }
        }
        $product_list = Hmodel\Activity::getActivityBargainProducts($type, 10, 0);
        $view = new view();
        $view->assign('bargainirgList',$product_list);
        if ($type == 0) {
            return $view->fetch('bargainirg');
        } else {
            return $view->fetch('bargainirg_live');
        }

    }

    //砍价活动\商品详情\查看贡献度\请帮忙
    public function bargaindetailAction()
    {

        $this->checkUserLogin();
        $uid = session('userinfo.uid');
        // $uid = 3;
        $seting_id = input('param.id',0,'int');
        $seting_info = Hmodel\Activity::getActivityProductsSeting($seting_id);  //砍价活动商品设置
        $bargain_section2 = !empty($seting_info['bargain_section2']) ? $seting_info['bargain_section2'] : 'no seting';
        if (!is_not_empty_array($seting_info)) notFund();

        $bargain_progress = Hmodel\Activity::returnProgressData( $seting_id, $seting_info['product_id'], $uid, $seting_info['attr1_id'],$seting_info['attr2_id'],
            $seting_info['add_money'],$seting_info['type']);

        if (!is_not_empty_array($bargain_progress) || $bargain_progress['user_id'] != $uid) notFund();

        $username       = session('userinfo.username');
        $user_info      = Hmodel\User::getuser_info($uid);
        $invite_code    = $user_info['invite_code'];
        $encrypt_code   = encrypt_hopeband($bargain_progress['id'] . '(&)' .$bargain_progress['activity_bargain_id'] . '(&)' .$uid . '(&)' . $invite_code . '(&)'
            . $seting_info['product_id'] . '(&)' . $seting_info['activity_money'] . '(&)' . $seting_info['bargain_section'] .  '(&)' . $seting_info['bargain_section2'] .'(&)'
            . $seting_info['join_count'] . '(&)'. $bargain_progress['type'], 'E', 'Hp_HopeBand_Bargainirg');

        //是否已经下单
        // $is_addorder    = Hmodel\Activity::checkIsAddorder($bargain_progress['id']);
        $is_addorder    = $bargain_progress['is_addorder'];

        //帮助列表
        $assistor_list = Hmodel\Activity::getAssistorList($bargain_progress['id']);

        $view = new view();
        $view->assign([
            'bar_code'           => $encrypt_code,
            'seting_info'        => $seting_info,
            'bargain_progress'   => $bargain_progress,
            'assistor_list'      => $assistor_list,
            'seting'             => $seting_id,
            'is_addorder'        => $is_addorder
        ]);
        $view->assign();
        return $view->fetch();

    }

    //帮忙砍价\进度\底部砍价商品列表
    public function bargainirgingAction ()
    {
        $url = $_SERVER['REQUEST_URI'];
        $encrypt_code = substr(substr($url,29),0,strpos(substr($url,29), '?invite_code'));

        $bargain_param = self::retrunBargainCode($encrypt_code);
        $bargain_id          = $bargain_param['bargain_id'];
        $bargainInfo         = Hmodel\Activity::getBargainirgProgress($bargain_id);
        if ( !is_not_empty_array($bargain_param) || !is_not_empty_array($bargainInfo)) {
            notFund();
        }

        $is_addorder = $bargainInfo['is_addorder'] == 1 ? true : false;

        $uid = session('userinfo.uid');
        $activity_product_id = $bargain_param['activity_product_id'];

        if ($bargain_param['sponsor_uid'] == $uid) {
            $this->redirect('bargaindetail',['id' => $activity_product_id]);
        }
        $product_id          = $bargain_param['product_id'];

        $bargain_list        = Hmodel\Activity::getActivityBargainProducts($bargain_param['type'], 999); //所有参与砍价活动的商品

        foreach ($bargain_list as $v) {
            if ( $v['id'] == $activity_product_id) {
                $product_info = $v;
            }
        }

        if (!is_not_empty_array($product_info)) notFund();
        $type = $bargain_param['type'];
        $activity_bargain_url = url('activity/bargainirg') ;

        $view = new view();
        $view->assign([
            'bar_code'      => $encrypt_code,   //邀请码
            'bargainInfo'   => $bargainInfo,    //当前砍价进度
            'product_info'  => $product_info,   //商品详情
            'bargain_list'  => $bargain_list,   //底部相关推荐
            'is_addorder'   => $is_addorder,     //是否入库
            'activity_bargain_url' => $activity_bargain_url
        ]);

        return $view->fetch();


    }

    //ajax砍价
    public function goBargainAction ()
    {
        if (Request::isAjax()) {

            $uid = session('userinfo.uid');
            $username = session('userinfo.username');
            $encrypt_code  = input('post.bar_code', '', 'string');
            if (empty($uid) || empty($username)) {
                $this->checkUserLogin();
            }
            $bargain_param = self::retrunBargainCode($encrypt_code);
            if (!is_not_empty_array($bargain_param)) {
                echo json_encode(array('status' => -3, 'info' => '不明错误,请联系客服'));die;
            }

            $seting_info = Hmodel\Activity::getActivityProductsSeting($bargain_param['activity_product_id']);  //砍价活动商品设置
            $stock = Hmodel\CategoryAttr::getproductstockbyidsonattr($seting_info['product_id'],$seting_info['attr1_id'],$seting_info['attr2_id']);

            if ($stock['category_sum'] < 1) {
                echo json_encode(['status' => -1, 'info' => '已抢光!']);die;
            }


            $userinfo = Hmodel\User::getuser_info($uid);
            $register_time = $userinfo['create_time'];
            $is_new_user = false;           //用户状态[default:老用户]
            if (($register_time + (60 * 60 * 8)) > time() && Hmodel\Activity::checkUserIsbargainEd($uid) === false) {
                $is_new_user  = true;       //是新用户
            }

            $sponsor_uid   = $bargain_param['sponsor_uid'];              //发起者id
            $bargain_id    = $bargain_param['bargain_id'];               //[activity_bargainirg]表主键id
            $join_count    = $bargain_param['join_count'];               //设置砍价次数
            $section       = $bargain_param['bargain_section'];          //砍价区间（老用户）
            $section2      = $bargain_param['bargain_section2'];         //砍价区间（新用户）
            $type          = $bargain_param['type'] == $seting_info['type'] ? $bargain_param['type'] : ''; //0：线上；  1：地推
            $activity_money= $bargain_param['activity_money'];           //活动最低价

            if (!is_not_empty_string($type)) {
                echo json_encode(array('status' => -3, 'info' => '不明错误,请联系客服'));die;
            }

            if ($uid == $sponsor_uid) {
                echo json_encode(array('status' => -1, 'info' => '不能给自己砍价'));die;
            }

            $state = Hmodel\Activity::checkPartBargain($bargain_id, $uid);  //是否帮伙伴砍过当前参与的进度

            if ( $state !== false) {
                echo  json_encode(array('status' => -2, 'info' => '您已帮伙伴砍掉' . $state . '元啦，不要再砍啦!'));die;
            }
            if ($type == 1 && $is_new_user === false) {
                echo json_encode(array('status' => -4, 'info' => '抱歉，该活动仅限新用户参加！'));die;
            }

            $state = Hmodel\Activity::givePartBargain($bargain_id, $sponsor_uid, $uid, $section, $section2, $join_count, $is_new_user,
                $activity_money, $type);
            if ($state == -1) {
                echo json_encode(array('status' => -3, 'info' => '已经最低价啦，不能再砍啦！'));die;
            }
            if ($state === false) {
                echo json_encode(array('status' => -3, 'info' => '哎呀，失败了！稍后帮我砍一次！'));die;
            } else {
                if ($is_new_user === true) {
                    echo json_encode(array('status' => 2, 'info' => '砍掉了' . $state .'元', 'deal_money' => $state));die;
                } else {
                    echo json_encode(array('status' => 1, 'info' => '成功帮伙伴砍掉' . $state .'元!', 'deal_money' => $state));die;
                }
            }

        }
    }

    //返回砍价活动相关数据
    public static function retrunBargainCode( $encrypt_str = '')
    {
        $data   = [];
        $code_str     = encrypt_hopeband($encrypt_str, 'D', 'Hp_HopeBand_Bargainirg');

        $code_arr     = explode('(&)', $code_str);


        if (is_not_empty_array($code_arr) && count($code_arr) == 10) {
            $data['bargain_id']             = $code_arr[0];             //砍价活动表主键id
            $data['activity_product_id']    = $code_arr[1];
            $data['sponsor_uid']            = $code_arr[2];             //砍价活动发起者uid
            $data['sponsor_invite_code']    = $code_arr[3];             //砍价活动发起者邀请码
            $data['product_id']             = $code_arr[4];             //砍价活动发起的商品id
            $data['activity_money']         = $code_arr[5];             //活动最低价格
            $data['bargain_section']        = $code_arr[6];             //老用户砍价区间
            $data['bargain_section2']       = $code_arr[7];             //新用户砍价区间
            $data['join_count']             = $code_arr[8];             //设置砍价次数
            $data['type']                   = $code_arr[9];             //设置砍价次数

        }

        return $data;
    }

    public function checkOrder2PayAction()
    {
        $this->checkUserLogin();
        if (!Request::isAjax()) { notFund(); }
        $seting_id = input('post.seting',0,'intval');
        $user_id   = session('userinfo.uid');
        //拿付款的额度和商品id
        $BargainPayData = Hmodel\Activity::getBargainResult2Pay($seting_id, $user_id);
        $stock = Hmodel\CategoryAttr::getproductstockbyidsonattr($BargainPayData['product_id'],$BargainPayData['attr1_id'],$BargainPayData['attr2_id']);
        if ($stock['category_sum'] < 1) {
            return json_encode(['status' => -2, 'info' => '已抢光!']);die;
        }
        if ($BargainPayData['is_addorder'] == 1) {
            return json_encode(['status' => -2, 'info' => '此商品已经购买过，不能重复购买！']);die;
        }
        if (!is_not_empty_array( $BargainPayData)) {
            return json_encode(['status' => -1, 'info' => '不明错误,请联系客服!']);die;
        }

        $product_id = $BargainPayData['product_id'];

        $attr1_name = '';
        $attr2_name = '';
        if (is_not_empty_array($attr1_info = Hmodel\Activity::getAttr1NameByAttrId($BargainPayData['attr1_id'], $product_id))){
            $attr1_name = $attr1_info['attr'];
        }
        if (is_not_empty_array($attr2_info = Hmodel\Activity::getAttr2NameByAttrId($BargainPayData['attr2_id'], $product_id))){
            $attr2_name = $attr2_info['attr'];
        }
        $data = [
            'product_id'  => $product_id,
            'prodcut_num' => 1,
            'attr1'       => $attr1_name,
            'attr2'       => $attr2_name,
            'seting_id'   => $seting_id
        ];
        return json_encode(['status' => 1, 'info' => $data]);

    }

    //查看砍价后的预付款订单信息
    public function createActivityOrderAction ()
    {
        $this->checkUserLogin();

        $uid = session('userinfo.uid');

        $product_num = 1;
        $attr1 = input("param.attr1", "" , "trim,string");
        $attr2 = input("param.attr2", "" , "trim,string");
        $seting_id = intval(input('param.seting_id', 0, 'intval'));
        $product_id  = intval(input("param.product_id", "" , "intval"));

        $pay_price_money = Hmodel\Activity::returnPayMoney($product_id, $seting_id, $uid);

        $type = $pay_price_money['type'];

        if (!is_not_empty_array($pay_price_money)) notFund();
        Cookie::set('ready_finish_bargain', encrypt_hopeband($pay_price_money['id'] . '(&)', 'E', 'hp_ready_bargain_pay'));
        $pay_info = $this->calculateFromProduct($product_id, $product_num, $attr1, $attr2, $uid , $pay_price_money['deal_money'], $type);
        $def_address = Hmodel\UserAddress::getDefAddress($uid);
        $view = new View();
        $view->assign('def_address',$def_address);
        $view->assign('product_carlist_bymerchantid',$pay_info['product_carlist_bymerchantid']);
        $view->assign('total_price',sprintf("%.2f",$pay_info['total_price']));

        $view->assign('total_delivery',$pay_info['total_delivery']);
        $view->assign('seting_id',$seting_id);




        return $view->fetch('createorder');
    }


}
